package com.wyp.didishige.activity.register;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.wyp.didishige.activity.BaseActivity;
import com.wyp.didishige.activity.MainActivity;
import com.wyp.didishige.activity.location.PoiSearchActivity;
import com.wyp.didishige.config.SheQuConstants;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.fragment.register.RegisterPhoneFragment;
import com.wyp.didishige.fragment.register.RegisterCommunity;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.OperationUtils;
import com.wyp.didishige.utils.PhotoUtil;
import com.wyp.didishige.utils.PreferenceHelper;
import com.wyp.didishige.utils.StringUtils;
import com.wyp.didishige.utils.SystemTool;
import com.wyp.didishige.utils.ToastUtil;
import com.wyp.didishige.wiget.ShiGeViewpager;
import com.wyp.didishige.R;
import com.wyp.didishige.fragment.register.RegisterAvatar;
import com.wyp.didishige.model.User;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.bmob.v3.listener.VerifySMSCodeListener;

/**
 * 注册页面
 */
public class RegisterWithMobileActivity extends BaseActivity implements OnClickListener {

    public User registerUser = new User();
    /**
     * 选择设置小区
     */
    public static final int SET_COMMUNITY_CODE = 0xff;
    Button btn_register, btn_last, btn_next;
    List<Fragment> fragments;
    ShiGeViewpager viewPager;
    PagerAdapter pagerAdapter;

    int currentPage = 0;
    RegisterPhoneFragment registerPhoneFragment;
    RegisterAvatar registerAvatar;
    RegisterCommunity registerCommunity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        actionBar=getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        layout_all = findViewById(R.id.layout_all);

        btn_last = (Button) findViewById(R.id.btn_last);
        btn_next = (Button) findViewById(R.id.btn_next);

        viewPager = (ShiGeViewpager) findViewById(R.id.viewpager);


        btn_register = (Button) findViewById(R.id.btn_register);

        assert btn_register != null;
        btn_register.setOnClickListener(this);

        btn_last.setOnClickListener(this);

        btn_next.setOnClickListener(this);
        initViewPager();
    }

    private void initViewPager() {
        registerPhoneFragment = new RegisterPhoneFragment();

        registerAvatar = new RegisterAvatar();
        registerCommunity = new RegisterCommunity();
        fragments = new ArrayList<Fragment>();

        fragments.add(registerPhoneFragment);
        fragments.add(registerAvatar);
        fragments.add(registerCommunity);

        pagerAdapter = new PagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == 0) {
                    btn_last.setEnabled(false);
                    btn_next.setVisibility(View.VISIBLE);
                } else if (position == 1) {
                    btn_last.setEnabled(true);
                    btn_next.setVisibility(View.VISIBLE);
                } else {
                    btn_last.setEnabled(true);
                    btn_next.setVisibility(View.GONE);
                    btn_register.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                if (registerCommunity.verfiy3()) {
                    register();
                }
                break;
            case R.id.btn_last:
                viewPager.setCurrentItem(--currentPage, true);
                btn_last.setVisibility(View.VISIBLE);
                btn_next.setVisibility(View.VISIBLE);
                btn_register.setVisibility(View.GONE);
                break;
            case R.id.btn_next:
                moveToNext();
                break;
        }
    }

    private void moveToNext() {
        switch (currentPage) {
            case 0:
                if (!StringUtils.isPhone(registerPhoneFragment.phoneNum.getText().toString())) {
                    ToastUtil.showShort(this, "手机号码格式不正确");
                    return;
                }

                isPhoneRegister(registerPhoneFragment.phoneNum.getText().toString());
                break;
            case 1:
                verifyStep2();
                break;
            case 2:

                break;
        }
    }

    private void isPhoneRegister(String phonenum) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("mobilePhoneNumber", phonenum);
        query.findObjects(this, new FindListener<User>() {
            @Override
            public void onSuccess(List<User> list) {
                if (list != null && list.size() > 0) {
                    ToastUtil.showShort(RegisterWithMobileActivity.this, "手机号码已注册");
                } else {
                    registerUser.setMobilePhoneNumber(registerPhoneFragment.phoneNum.getText().toString());
                    if (!StringUtils.isValidPsw(registerPhoneFragment.password.getText().toString())) {
                        ToastUtil.showShort(RegisterWithMobileActivity.this, "密码格式不正确");
                        return;
                    }
                    registerUser.setPassword(registerPhoneFragment.password.getText().toString());

                    String smsCode = registerPhoneFragment.code.getText().toString();
                    if (StringUtils.isNullOrEmpty(smsCode)) {
                        ToastUtil.showShort(RegisterWithMobileActivity.this, "请输入短信验证码");
                        return;
                    }

                    BmobSMS.verifySmsCode(RegisterWithMobileActivity.this, registerUser.getMobilePhoneNumber(), registerPhoneFragment.code.getText().toString(), new VerifySMSCodeListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                viewPager.setCurrentItem(++currentPage, true);
                            } else {
                                ToastUtil.showShort(RegisterWithMobileActivity.this, "验证失败,请再次获取验证码进行验证");
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {
                ToastUtil.showShort(RegisterWithMobileActivity.this, "校验失败请稍候重试 " + s);
            }
        });
    }

    public String headUrl;
    public File avatar;

    private void verifyStep2() {
        if (avatar == null) {
            ShowToast("请添加您的头像");
            return;
        }

        if (StringUtils.isNullOrEmpty(registerAvatar.user_nick.getText().toString())) {
            ToastUtil.showShort(this, "请填写昵称");
            return;
        }
        if (StringUtils.isNullOrEmpty(registerAvatar.birthday)) {
            ShowToast("请选择出生日期");
            return;
        }

        registerUser.setNick(registerAvatar.user_nick.getText().toString());
        registerUser.setSex(registerAvatar.male);
        registerUser.setUserBirthday(registerAvatar.birthday);
        uploadAvatar();
    }

    private void uploadAvatar() {
        if (avatar == null || "".equals(avatar)) {
            ShowToast("请上传头像");
            return;
        }
        final BmobFile bmobFile = new BmobFile(avatar);
        bmobFile.upload(this, new UploadFileListener() {

            @Override
            public void onSuccess() {
                headUrl = bmobFile.getFileUrl(RegisterWithMobileActivity.this);
                viewPager.setCurrentItem(++currentPage, true);
            }

            @Override
            public void onProgress(Integer arg0) {

            }

            @Override
            public void onFailure(int arg0, String msg) {
                ShowToast("注册失败,请重试");
            }
        });
    }

    class PagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;

        public PagerAdapter(FragmentManager fm, List<Fragment> list) {
            super(fm);
            this.fragments = list;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    private void register() {
        boolean isNetConnected = SystemTool.checkNet(this);
        if (!isNetConnected) {
            ShowToast(R.string.network_tips);
            return;
        }

        loading.setMessage("正在注册...");
        loading.setCanceledOnTouchOutside(false);
        loading.show();


        //将user和设备id进行绑定
        registerUser.setDeviceType("android");

        if (headUrl != null) {
            registerUser.setAvatar(headUrl);
        }
        registerUser.setUsername(registerUser.getMobilePhoneNumber());
        registerUser.setInstallId(BmobInstallation.getInstallationId(this));
        registerUser.signUp(RegisterWithMobileActivity.this, new SaveListener() {

            @Override
            public void onSuccess() {
                loading.dismiss();
                ShowToast("注册成功");
                // 将设备与username进行绑定
                sendBroadcast(new Intent(SheQuConstants.ACTION_REGISTER_SUCCESS_FINISH));
                Bundle bundle = new Bundle();
                bundle.putBoolean(Config.KEY_AFFTER_REGISTER_FIRSTER_DYNAMIC, true);
                User user = BmobUser.getCurrentUser(RegisterWithMobileActivity.this,User.class);
                if (user.getSex()) {
                    PreferenceHelper.write(RegisterWithMobileActivity.this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, true);
                } else {
                    PreferenceHelper.write(RegisterWithMobileActivity.this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false);
                }
                PreferenceHelper.write(RegisterWithMobileActivity.this, Config.PreferenceHelperfile, Config.KEY_NEW_FIRSTER_DYNAMIC, true);
                IntentUtil.start_activity(RegisterWithMobileActivity.this, MainActivity.class, bundle);
                finish();
            }

            @Override
            public void onFailure(int arg0, String arg1) {
                ShowToast("注册失败:" + arg1);
                loading.dismiss();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                back();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private void back() {
        switch (currentPage) {
            case 1:
            case 2:
            case 3:
            case 4:
                viewPager.setCurrentItem(--currentPage, true);
                btn_last.setVisibility(View.VISIBLE);
                btn_next.setVisibility(View.VISIBLE);
                btn_register.setVisibility(View.GONE);
                break;
            default:
                builder.setTitle("提示");
                builder.setMessage("是否退出注册");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        finish();
                    }
                });
                builder.show();
                break;
        }
    }

    private View layout_all;

    boolean isFromCamera = false;// 区分拍照旋转
    int degree = 0;
    public String filePath = "";
    RelativeLayout layout_choose;
    RelativeLayout layout_photo;
    public PopupWindow avatorPop;

    /**
     * 现实选择对话框
     */
    public void showAvatarPop() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_showavator,
                null);
        layout_choose = (RelativeLayout) view.findViewById(R.id.layout_choose);
        layout_photo = (RelativeLayout) view.findViewById(R.id.layout_photo);
        layout_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                layout_choose.setBackgroundColor(getResources().getColor(
                        R.color.base_color_text_white));
                layout_photo.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.pop_bg_press));
                File dir = SheQuConstants.SHEQU_HEAD;
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                // 原图
                File file = new File(dir, new SimpleDateFormat("yyMMddHHmmss")
                        .format(new Date()));
                filePath = file.getAbsolutePath();// 获取相片的保存路径
                Uri imageUri = Uri.fromFile(file);

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent,
                        SheQuConstants.REQUESTCODE_UPLOADAVATAR_CAMERA);
            }
        });
        layout_choose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                layout_photo.setBackgroundColor(getResources().getColor(
                        R.color.base_color_text_white));
                layout_choose.setBackgroundDrawable(getResources().getDrawable(
                        R.drawable.pop_bg_press));
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent,
                        SheQuConstants.REQUESTCODE_UPLOADAVATAR_LOCATION);
            }
        });

        avatorPop = new PopupWindow(view, mScreenWidth, 600);
        avatorPop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    avatorPop.dismiss();
                    return true;
                }
                return false;
            }
        });
        avatorPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        avatorPop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        avatorPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        avatorPop.setTouchable(true);
        avatorPop.setFocusable(true);
        avatorPop.setOutsideTouchable(true);
        avatorPop.setBackgroundDrawable(new BitmapDrawable());
        // 动画效果 从底部弹起
        avatorPop.setAnimationStyle(R.style.Animations_GrowFromBottom);
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int winHeight =getWindow().getDecorView().getHeight();
        avatorPop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0,winHeight-rect.bottom);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case SheQuConstants.REQUESTCODE_UPLOADAVATAR_CAMERA:// 拍照修改头像
                    if (!Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        ShowToast("SD不可用");
                        return;
                    }

                    isFromCamera = true;
                    File file = new File(filePath);
                    degree = PhotoUtil.readPictureDegree(file.getAbsolutePath());
                    Log.i("life", "拍照后的角度：" + degree);
                    OperationUtils.startImageAction(RegisterWithMobileActivity.this, Uri.fromFile(file), 200, 200,
                            SheQuConstants.REQUESTCODE_UPLOADAVATAR_CROP, true);
                    break;
                case SheQuConstants.REQUESTCODE_UPLOADAVATAR_LOCATION:// 本地修改头像
                    if (avatorPop != null) {
                        avatorPop.dismiss();
                    }
                    Uri uri = null;
                    if (data == null) {
                        return;
                    }
                    if (!Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        ShowToast("SD不可用");
                        return;
                    }
                    isFromCamera = false;
                    uri = data.getData();
                    String uriPath = uri.getPath();
                    OperationUtils.startImageAction(RegisterWithMobileActivity.this, uri, 200, 200,
                            SheQuConstants.REQUESTCODE_UPLOADAVATAR_CROP, true);
                    break;
                case SheQuConstants.REQUESTCODE_UPLOADAVATAR_CROP:// 裁剪头像返回
                    if (avatorPop != null) {
                        avatorPop.dismiss();
                    }
                    if (data == null) {
                        // Toast.makeText(this, "取消选择", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        saveCropAvator(data);
                    }
                    // 初始化文件路径
                    filePath = "";

                    break;
                case SET_COMMUNITY_CODE:
                    if (data != null && data.getExtras() != null) {
                        String address = data.getExtras().getString(PoiSearchActivity.ADDRESS);
                        registerUser.setCommunity(address);
                        registerCommunity.setUserCommunity(address);
                    }
                    break;
                default:
                    break;

            }
        } else {
            if (avatorPop != null) {
                avatorPop.dismiss();
            }
        }
    }

    /**
     * 保存裁剪的头像
     *
     * @param data
     */
    private void saveCropAvator(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            Log.i("life", "avatar - bitmap = " + bitmap);
            if (bitmap != null) {
                bitmap = PhotoUtil.toRoundCorner(bitmap, 10);
                if (isFromCamera && degree != 0) {
                    bitmap = PhotoUtil.rotaingImageView(degree, bitmap);
                }
                String fileName = String.format("%s.png",new SimpleDateFormat("yyyyMMddHHmm").format(new Date()));
                avatar = new File(SheQuConstants.SHEQU_HEAD,fileName);
                registerAvatar.user_head.setImageBitmap(bitmap);
                PhotoUtil.saveBitmap(SheQuConstants.SHEQU_HEAD,fileName,bitmap,true);
                refreshAvatar();
                if (bitmap!=null&&bitmap.isRecycled()){
                    bitmap.recycle();
                }
            }
        }
    }

    /**
     * 更新头像 refreshAvatar
     *
     * @return void
     * @throws
     */
    private void refreshAvatar() {
        if (avatar != null && !avatar.equals("")) {
            BitmapDrawable bitmapDrawable = new BitmapDrawable(avatar.getAbsolutePath());
            registerAvatar.user_head.setImageDrawable(bitmapDrawable);
            registerAvatar.user_head.setVisibility(View.VISIBLE);
            registerAvatar.add_user_avator_lay.setVisibility(View.GONE);
        } else {
            ToastUtil.showShort(RegisterWithMobileActivity.this, "设置失败请重新添加头像");
            registerAvatar.user_head.setImageResource(R.drawable.ic_launcher);
        }
    }
}
